<template>
    <div>

        <div class="container">
            <div class="table_btn">

                <label class="table-label">任务名称:</label>
                <el-input v-model="query.jobName"  placeholder="任务名称" class="menu-input" clearable></el-input>

                <label class="table-label">任务分组:</label>
                <el-select class="menu-input" v-model="query.jobGroup" placeholder="请选择">
                    <el-option
                            v-for="item in jobGroupOptions"
                            :key="item.key"
                            :label="item.value"
                            :value="item.key">
                    </el-option>
                </el-select>

                <label class="table-label">任务状态:</label>
                <el-select class="menu-input" v-model="query.status" placeholder="请选择">
                    <el-option
                            v-for="item in statusOptions"
                            :key="item.key"
                            :label="item.value"
                            :value="item.key">
                    </el-option>
                </el-select>

                <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>

                <el-button type="default" icon="el-icon-refresh" @click="searchReset">重置</el-button>

            </div>

            <div class="table_btn">
                <el-button type="success" icon="el-icon-edit" @click="add($event)">添加</el-button>
                <el-button type="danger" icon="el-icon-delete"  @click="del()" >批量删除</el-button>
            </div>

            <div class="box_table">
                <el-table
                        :data="tableData"
                        border
                        @selection-change="handleSelectionChange"
                        style="width: 100%">

                    <el-table-column
                            type="selection"
                            width="55">
                    </el-table-column>

                    <el-table-column
                            prop="job_id"
                            label="序号"
                            width="50">
                    </el-table-column>

                    <el-table-column
                            prop="job_name"
                            label="任务名称">
                    </el-table-column>

                    <el-table-column
                            prop="job_group"
                            label="任务分组"
                            width="100">
                    </el-table-column>

                    <el-table-column
                            prop="invoke_target"
                            label="执行方法名"
                            width="180">
                    </el-table-column>

                    <el-table-column
                            prop="cron_expression"
                            label="执行表达式"
                            width="100">
                    </el-table-column>

                    <el-table-column
                            prop="status"
                            label="任务状态"
                            width="180">

                        <template slot-scope="scope">

                            <el-switch v-model="scope.row.status"
                                       active-text="启用"
                                       inactive-text="停止"
                                       :active-value="1"
                                       :inactive-value="0"
                                        @change="changeStatus($event,scope.row)">
                            </el-switch>

                        </template>
                    </el-table-column>

                    <el-table-column
                            prop="misfire_policy"
                            label="执行策略"
                            width="100">
                        <template slot-scope="scope">
                            {{scope.row.misfire_policy  == 1 ? "重复执行" : "执行一次"}}
                        </template>
                    </el-table-column>

                    <el-table-column
                            prop="create_time"
                            label="创建时间"
                            :formatter="dateFormat">
                    </el-table-column>

                    <el-table-column label="操作" width="200">
                        <template slot-scope="scope">

                            <el-button
                                    size="mini"
                                    icon="el-icon-edit"
                                    type="primary"
                                    @click="edit(scope.$index, scope.row)">
                                编辑
                            </el-button>

                            <el-button
                                    size="mini"
                                    type="danger"
                                    icon="el-icon-delete"
                                    @click="del(scope.row.job_id)">
                                删除
                            </el-button>

                        </template>
                    </el-table-column>

                </el-table>
            </div>
            <div class="pagination">
                <el-pagination
                        background
                        layout="total, prev, pager, next"
                        :total="pageTotal"
                        :current-page.sync="currentPage"
                        :page-size="pageSize"
                        @current-change="handlePageChange"></el-pagination>
            </div>
        </div>

        <!--添加-->
        <el-dialog title="添加任务" :visible.sync="addDialogVisible"  width="35%">
            <el-form :model="form" :rules="rules" ref="form" label-width="100px">

                <el-form-item label="任务名称" prop="jobName">
                    <el-input v-model="form.jobName" placeholder="请输入纯英文字母"></el-input>
                </el-form-item>


                <el-form-item label="任务分组" prop="jobGroup">
                    <el-select
                            v-model="form.jobGroup"
                            placeholder="请选择"
                            collapse-tags>
                        <el-option
                                v-for="item in jobGroupFormOptions"
                                :key="item.key"
                                :label="item.value"
                                :value="item.key">
                        </el-option>
                    </el-select>

                </el-form-item>



                <el-form-item label="执行方法名" prop="invokeTarget">
                    <el-input v-model="form.invokeTarget" placeholder="以|分隔多个参数 示例：param1|param1"></el-input>
                </el-form-item>

                <el-form-item label="cron表达式" prop="cronExpression">
                    <el-input v-model="form.cronExpression"></el-input>
                    <ul style="list-style: none;">
                        <li><i class="el-icon-warning"></i> */5 * * * * ? : 每隔5秒执行一次</li>
                        <li><i class="el-icon-warning"></i> 20 */1 * * * ? : 每隔1分钟执行一次</li>
                        <li><i class="el-icon-warning"></i> 30 0 23 * * ? : 每天23点执行一次</li>
                        <li><i class="el-icon-warning"></i> 0 0 1 * * ? : 每天凌晨1点执行一次</li>
                        <li><i class="el-icon-warning"></i> 0 0 1 1 * ? : 每月1号凌晨1点执行一次</li>
                    </ul>
                </el-form-item>

                <el-form-item label="执行策略" prop="misfirePolicy">
                    <el-radio-group v-model="form.misfirePolicy">
                        <el-radio  v-for="item in jobPolicyFormOptions"
                                   :key="item.key"
                                   :label="item.key">{{item.value}}</el-radio>
                    </el-radio-group>
                </el-form-item>

                <el-form-item label="状态" prop="status">
                    <el-switch v-model="form.status"
                               active-text="启用"
                               inactive-text="停止"
                               :active-value="1"
                               :inactive-value="0">
                    </el-switch>
                </el-form-item>

                <el-form-item label="备注" prop="remark">
                    <el-input  type="textarea"
                               placeholder="请输入备注"
                               :rows="2"
                               v-model="form.remark">
                    </el-input>
                </el-form-item>

                <el-form-item>
                    <el-button
                            type="primary"
                            @click="submitAdd('form')"
                            :loading="addLoading">立即创建</el-button>
                    <el-button @click="resetForm('form')">重置</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>


        <!-- 编辑 -->
        <el-dialog title="编辑任务" :visible.sync="editDialogVisible"  width="35%">
            <el-form :model="editForm" :rules="editRules" ref="edit_form" label-width="100px">

                <el-form-item label="任务名称" prop="jobName">
                    <el-input v-model="editForm.jobName" placeholder="请输入纯英文字母"></el-input>
                </el-form-item>


                <el-form-item label="任务分组" prop="jobGroup">
                    <el-select
                            v-model="editForm.jobGroup"
                            placeholder="请选择"
                            collapse-tags>
                        <el-option
                                v-for="item in jobGroupEditFormOptions"
                                :key="item.key"
                                :label="item.value"
                                :value="item.key">
                        </el-option>
                    </el-select>

                </el-form-item>


                <el-form-item label="执行方法名" prop="invokeTarget">
                    <el-input v-model="editForm.invokeTarget" placeholder="以|分隔多个参数 示例：param1|param1"></el-input>
                </el-form-item>

                <el-form-item label="cron表达式" prop="cronExpression">
                    <el-input v-model="editForm.cronExpression"></el-input>
                    <ul style="list-style: none;">
                        <li><i class="el-icon-warning"></i> */5 * * * * ? : 每隔5秒执行一次</li>
                        <li><i class="el-icon-warning"></i> 20 */1 * * * ? : 每隔1分钟执行一次</li>
                        <li><i class="el-icon-warning"></i> 30 0 23 * * ? : 每天23点执行一次</li>
                        <li><i class="el-icon-warning"></i> 0 0 1 * * ? : 每天凌晨1点执行一次</li>
                        <li><i class="el-icon-warning"></i> 0 0 1 1 * ? : 每月1号凌晨1点执行一次</li>
                    </ul>
                </el-form-item>

                <el-form-item label="执行策略" prop="misfirePolicy">
                    <el-radio-group v-model="editForm.misfirePolicy">
                        <el-radio  v-for="item in jobPolicyEditFormOptions"
                                   :key="item.key"
                                   :label="item.key">{{item.value}}</el-radio>
                    </el-radio-group>
                </el-form-item>

                <el-form-item label="状态" prop="status">
                    <el-switch v-model="editForm.status"
                               active-text="启用"
                               inactive-text="停止"
                               :active-value="1"
                               :inactive-value="0">
                    </el-switch>
                </el-form-item>

                <el-form-item label="备注" prop="remark">
                    <el-input  type="textarea"
                               placeholder="请输入备注"
                               :rows="2"
                               v-model="editForm.remark">
                    </el-input>
                </el-form-item>

                <el-form-item>
                    <el-button
                            type="primary"
                            @click="submitEdit('edit_form')"
                            :loading="editLoading">立即创建</el-button>
                    <el-button @click="resetForm('edit_form')">重置</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>


    </div>
</template>
<script>

    import utils  from "@/utils/function"
    const  { request,dateFormat } = utils
    import mixin from "@/utils/mixin"
    import Paging from "@/utils/paging"
    const paging = new Paging("/system/monitor/job/list")

    export default {
        mixins: [mixin],
        data() {
            let rules = {
                jobName: [
                    { required: true, message: '请输入任务名称', trigger: 'blur' },
                    { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
                ],
                jobGroup:[
                    { required: true, message: '请选择任务分组', trigger: 'change' }
                ],
                invokeTarget:[
                    { required: true, message: '请输入执行方法名', trigger: 'blur' },
                    { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
                ],
                jobParams:[
                    { required: true, message: '请输入执行参数', trigger: 'blur' },
                    { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
                ],
                cronExpression:[
                    { required: true, message: '请输入cron表达式', trigger: 'blur' }
                ]
            }
            return {
                tableData: [],
                pageTotal: 0,
                multipleSelection:[],           //列表中checkbox选中的值
                query: {                        //查询数据
                    jobName:"",
                    jobGroup:"",
                    status:""
                },
                jobGroupOptions:[],
                statusOptions:[],

                jobGroupFormOptions:[],
                statusFormOptions:[],
                jobPolicyFormOptions:[],

                jobGroupEditFormOptions:[],
                jobStatusEditFormOptions:[],
                jobPolicyEditFormOptions:[],


                currentPage:1,
                pageSize:5,
                addDialogVisible:false,
                rules:rules,
                form:{
                    jobName:'',
                    jobGroup:'',
                    invokeTarget:'',
                    jobParams:'',
                    cronExpression:'',
                    misfirePolicy:'1',
                    remark:'',
                    status:0
                },
                addLoading:false,

                editDialogVisible:false,
                editRules:rules,
                editLoading:false,
                editForm:{
                    jobId:0,
                    jobName:'',
                    jobGroup:'',
                    invokeTarget:'',
                    jobParams:'',
                    cronExpression:'',
                    misfirePolicy:'1',
                    remark:'',
                    status:0
                }

            }
        },
        created() {
            this.getUserList({page:1,pageSize:this.pageSize})
        },
        methods: {

            changeStatus(value,row){
                var id = row.job_id
                var url = ''
                if(value === 0){
                    url = '/system/monitor/job/start'
                } else if(value === 1){
                    url = '/system/monitor/job/stop'
                }
                request.loading().post(url,{id}).then(response=>{
                    let {code,data,msg} = response

                    if(code === 0){
                        this.$message({
                            message: msg,
                            type: 'success'
                        });
                    } else {
                        this.$message.error(msg);
                    }
                })
            },
            add(){
                request.loading().get('/system/monitor/job/add').then(response=>{
                    let {code,data:{jobGroup,jobStatus,jobPolicy},msg} = response

                    if(code === 0 ){

                        if(jobGroup && _.isArray(jobGroup.values)){
                            this.jobGroupFormOptions = jobGroup.values
                        }

                        if(jobStatus && _.isArray(jobStatus.values)){
                            this.statusFormOptions = jobStatus.values
                        }

                        if(jobPolicy && _.isArray(jobPolicy.values)){
                            this.jobPolicyFormOptions = jobPolicy.values
                        }

                        this.addDialogVisible = true
                    } else {
                        this.$message.error(msg);
                    }

                })

            },
            submitAdd(form){
                this.$refs[form].validate((valid) => {
                    if (valid) {
                        this.addLoading = true
                        request.post("/system/monitor/job/add",this.form).then(response=>{
                            this.addLoading = false
                            let {code,data,msg}  = response
                            if(code === 0 ){
                                this.$message.success(msg);
                                this.addDialogVisible = false
                                this.getUserList({page:1})
                                this.resetForm('form')
                            } else {
                                this.$message.error(msg);
                            }
                        })
                    } else {
                        console.log('error submit!!');
                        return false;
                    }
                })
            },
            del(id){
                if(id){
                    this._del(id)
                } else {
                    if(this.multipleSelection.length < 1){
                        this.$message.error('选择要删除的数据');
                        return ;
                    }

                    this._del(this.multipleSelection.map(value => value.job_id))
                }
            },

            _del(ids){
                this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    if(_.isNumber(ids)){
                        ids = [ids]
                    }
                    if(!_.isArray(ids)){
                        return false;
                    }
                    request.loading().post("/system/monitor/job/delete",{ids:ids}).then(response=>{
                        let {code,data,msg} = response
                        if(code === 0){
                            this.getUserList({page:this.currentPage})
                            this.$message({
                                type: 'success',
                                message: '删除成功!'
                            });
                        } else {
                            this.$message.error(msg);
                        }
                    }).catch(error=>{
                        console.log(error);
                    });

                }).catch((error) => {
                    console.log(error);
                    this.$message({
                        type: 'info',
                        message: '删除失败，请重试!'
                    });
                });
            },
            edit(index,row){
                const id = row.job_id
                request.loading().get('/system/monitor/job/edit',{id}).then(response=>{
                    let {code,data:{jobGroup,jobInfo,jobStatus,jobPolicy},msg} = response
                    if(code === 0){

                        if(jobGroup && _.isArray(jobGroup.values)){
                            this.jobGroupEditFormOptions = jobGroup.values
                        }

                        if(jobPolicy && _.isArray(jobPolicy.values)){
                            this.jobPolicyEditFormOptions = jobPolicy.values
                        }

                        let {
                            job_id,
                            job_name,
                            job_params,
                            job_group,
                            invoke_target,
                            cron_expression,
                            misfire_policy,
                            concurrent,
                            status,
                            create_by,
                            create_time,
                            update_by,
                            update_time,
                            remark
                        } = jobInfo
                        this.editForm.jobId = job_id
                        this.editForm.jobName = job_name
                        this.editForm.jobGroup = job_group
                        this.editForm.invokeTarget = invoke_target
                        this.editForm.jobParams = job_params
                        this.editForm.cronExpression = cron_expression
                        this.editForm.misfirePolicy = misfire_policy+''
                        this.editForm.remark = remark
                        this.editForm.status = status

                        this.editDialogVisible = true
                    } else {
                        this.$message.error(msg);
                    }

                })
            },
            submitEdit(form){
                this.$refs[form].validate((valid) => {
                    if (valid) {
                        this.editLoading = true
                        request.post("/system/monitor/job/edit",this.editForm).then(response=>{
                            this.editLoading = false
                            let {code,data,msg}  = response
                            if(code === 0 ){
                                this.$message.success(msg);
                                this.editDialogVisible = false
                                this.getUserList({page:1})
                                this.resetForm(form)
                            } else {
                                this.$message.error(msg);
                            }
                        })
                    } else {
                        console.log('error submit!!');
                        return false;
                    }
                })
            },
            resetForm(formName){
                this.$refs[formName].resetFields();
            },

            handlePageChange(val) {             //获取分页数据
                this.currentPage = val
                this.getUserList({page:val})
            },
            handleSearch(){             //查询
                paging.setQuery( _.cloneDeep(this.query) );
                this.handlePageChange(1)
            },
            searchReset(){                  //查询重置
                _.forOwn(this.query,(value, key)=>{
                    this.$set(this.query,key,'')
                })
                this.handleSearch()
            },
            getUserList(param){           //获取列表数据
                paging.request(param).then(response=>{
                    let {code,data:{total,list,searchGroup,searchStatus},msg} = response
                    if(code === 0){
                        this.pageTotal = total
                        if(_.isArray(list) && list.length > 0){
                            this.tableData = list
                        } else {
                            this.tableData = []
                        }

                        if(_.isArray(searchGroup.values)){
                            this.jobGroupOptions = searchGroup.values
                        }

                        if(_.isArray(searchStatus.values)){
                            this.statusOptions = searchStatus.values
                        }

                    } else {
                        this.$message.error(msg);
                    }
                }).catch(error=>{
                    console.log(error);
                });
            },

            handleSelectionChange(val) {        //列表中checkbox选中事件
                this.multipleSelection = val;
            }
        }

    }
</script>
<style lang="scss" scoped>

</style>
